package fr.liglab.adele.icasa.house.device.impl;

import java.io.IOException;
import java.io.InputStream;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.ServiceProperty;

import fr.liglab.adele.icasa.device.DeviceListener;
import fr.liglab.adele.icasa.device.light.BinaryLight;
import fr.liglab.adele.icasa.device.presence.AudioSource;
import fr.liglab.adele.icasa.device.presence.Speaker;
import fr.liglab.adele.icasa.device.util.AbstractDevice;
import fr.liglab.adele.icasa.environment.SimulatedDevice;
import fr.liglab.adele.icasa.environment.SimulatedEnvironment;

@Component
@Provides
@Instantiate
public class SimulatedSpeakerImpl extends AbstractDevice implements Speaker,
		Runnable, SimulatedDevice {

	@ServiceProperty(name = BinaryLight.DEVICE_SERIAL_NUMBER, mandatory = true)
	private String m_serialNumber;
	
	Thread curr = null;

	AudioSource source = null;

	boolean isPlaying;

	public boolean isPlaying() {
		return isPlaying;
	}

	public SimulatedSpeakerImpl() {

	}

	public String getSerialNumber() {
		// TODO Auto-generated method stub
		return m_serialNumber;
	}

	public void addListener(DeviceListener listener) {
		// TODO Auto-generated method stub

	}

	public void removeListener(DeviceListener listener) {
		// TODO Auto-generated method stub

	}

	public void fadeout() {
		// TODO Auto-generated method stub

	}

	public void fadein() {
		// TODO Auto-generated method stub

	}

	public void setSource(AudioSource ias) {
		this.source = ias;
		turnon();

	}

	public void unsetSource() {
		// TODO Auto-generated method stub
		this.source = null;
		 turnoff();
	}

	public void turnoff() {

		isPlaying = false;
		if (curr != null) {
			curr.interrupt();
		}
	}

	public void turnon() {
		isPlaying = true;
		curr = new Thread(this);
	}

	public void run() {
		// TODO Auto-generated method stub

		AudioSource currSource = source;

		while (currSource != null) {

			try {
				InputStream info = currSource.getStream();

				if (info == null)
					continue;

				int data = info.read();

				if (data != -1)
					System.out.print(data);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		isPlaying = false;

	}

	public String getEnvironmentId() {
		// TODO Auto-generated method stub
		return null;
	}

	public void bindSimulatedEnvironment(SimulatedEnvironment environment) {
		// TODO Auto-generated method stub

	}

	public void unbindSimulatedEnvironment(SimulatedEnvironment environment) {
		// TODO Auto-generated method stub

	}

}
